/**
 * Created by jf on 2015/9/11.
 */

var pageManager;
$(function () {
    pageManager = {
        $tabbar: $('.weui-tabbar__item'),
        $container: $('.js_container'),
        _pageStack: [],
        _configs: [],
        _nav: [],
        _point: '',
        _defaultPage: "child_page_1",
        _isGo: false,
        default: function (defaultPage) {
            this._defaultPage = defaultPage;
            return this;
        },
        init: function () {
            var self = this;

            self.$container.on('click', '.weui-click__go', function () {
                var to = $(this).data('go');
                var url = $(this).data('url');
                self.go(to, url);
            });

            self.$container.on('click', '.weui-click__alert', function () {
                var selecter = $(this).data('dom');
                var img = null;
                if (selecter) {
                    img = $(this).find(selecter).html();
                } else {
                    img = $(this).html();
                }
                $.alert(img, '');
            });

            self.$container.on('click', '.weui-click__post', function () {
                var query;
                if ($(this).data('form')) {
                    var dom = $(this).closest('.page');
                    var form = dom.find($(this).data('form'));
                    query = form.serialize();
                } else if ($(this).data('ids')) {
                    query = 'ids=' + $(this).data('ids');
                } else {
                    $.toast('没有数据', 'forbidden');
                    return;
                }
                var url = $(this).data('url');
                self.ajax_post(query, url);
            });

            $(window).on('hashchange', function (e) {
                var _isBack = !self._isGo;
                self._isGo = false;
                if (!_isBack) {
                    return;
                }

                var url = location.hash.indexOf('#') === 0 ? location.hash : '#';
                var found = null;
                for (var i = 0, len = self._pageStack.length; i < len; i++) {
                    var stack = self._pageStack[i];
                    if (stack.config.url === url) {
                        found = stack;
                        break;
                    }
                }
                if (found) {
                    self.back();
                    if (found.config.save) {
                        self._nav_action(found.config.navigation);
                    }
                } else {
                    $.confirm({
                        title: '离开？',
                        text: '将要离开当前应用',
                        onOK: function () {
                            window.WeixinJSBridge.invoke('closeWindow', {}, function (res) {
                            });
                        },
                        onCancel: function () {
                            var oldURL = e.originalEvent.oldURL;
                            oldURL = oldURL.split("#")[1];
                            self._isGo = true;
                            location.hash = oldURL;
                        }
                    });
                }
            });

            function goDefault() {
                var page = self._find('name', self._defaultPage);
                for (var stack in self._pageStack) {
                    self._pageStack[stack].dom.remove();
                }
                self._pageStack = [];
                self.go(page.name);
            }

            goDefault();

            return this;
        },
        //添加页面队列，config为其配置
        push: function (config) {
            var that = this;
            var puch_config = config;
            var target = $(config.template);
            puch_config.action = target.data('action');
            if (target.data('step') == 'save') {
                puch_config.save = true;
            }
            this._configs.push(puch_config);
            if (puch_config.action) {
                if (puch_config.save) {
                    that._ajax_load(puch_config.action, puch_config.name);
                }
            }//进行页面预载
            return this;
        },

        //执行虚拟跳转，to目标scrip，action为指定url
        go: function (to, action) {
            var config = this._find('name', to);
            var html;
            var that = this;
            if (!config) {
                that._ajax_go(action);
                return that;
            }

            //如果预先加载
            html = $(config.template).html();//获取加载的html
            var $html = $(html).addClass(config.name);
            if (this._pageStack.length > 0) {
                $html.addClass('slideIn');
            }
            $html.on('animationend webkitAnimationEnd', function () {
                $html.removeClass('slideIn').addClass('js_show');
            });
            this.$container.append($html);//容器内注入
            this._pageStack.push({
                config: config,
                dom: $html
            });//堆栈添加纪录

            if (config.navigation != null) {
                this._nav_action(config.navigation);//激活导航高亮
                this._point = config.navigation;//指针指向nav
            }

            this._isGo = true;
            location.hash = config.url;

            if (!config.isBind) {
                this._bind(config);
            }//绑定js（没用过）

            return this;
        },
        //返回上一页
        back: function () {
            var stack = this._pageStack.pop();
            if (!stack) {
                return;
            }

            stack.dom.addClass('slideOut').on('animationend', function () {
                stack.dom.remove();
            }).on('webkitAnimationEnd', function () {
                stack.dom.remove();
            });

            return this;

        },
        _find: function (key, value) {
            var page = null;
            for (var i = 0, len = this._configs.length; i < len; i++) {
                if (this._configs[i][key] === value) {
                    page = this._configs[i];
                    break;
                }
            }
            return page;
        },
        _bind: function (page) {
            var events = page.events || {};
            for (var t in events) {
                for (var type in events[t]) {
                    this.$container.on(type, t, events[t][type]);
                }
            }
            page.isBind = true;
        },
        _ajax_go: function (url) {
            var result;
            $.ajax({
                type: "GET",
                cache: false,
                // async: false,
                url: url,
                success: function (data) {
                    var page, html;
                    var name = url.substring(url.lastIndexOf('/') + 1);
                    name = name.replace('?', '_');
                    name = name.replace('=', '_');
                    name = name.replace('&', '_');
                    page = {
                        name: name,
                        action: url,
                        url: "#" + name
                    };
                    html = data;
                    var $html = $(html).addClass('slideIn').addClass(page.name);
                    $html.on('animationend webkitAnimationEnd', function () {
                        $html.removeClass('slideIn').addClass('js_show');
                    });
                    pageManager.$container.append($html);
                    pageManager._pageStack.push({
                        config: page,
                        dom: $html
                    });
                    // pageManager._nav_action(page.navigation);
                    // pageManager._point = page.navigation;
                    // pageManager._isGo = true;
                    pageManager._isGo = true;
                    location.hash = page.name;

                    if (!page.isBind) {
                        pageManager._bind(page);
                    }
                }, error: function (data) {
                    $.toast('加载页面超时', "forbidden");
                }
            });
        },
        _ajax_load: function (url, name) {
            var result;
            $.ajax({
                type: "GET",
                cache: false,
                // async: false,
                url: url,
                template: name,
                success: function (data) {
                    var page;
                    page = pageManager._find('name', name);
                    $(page.template).html(data);
                    if (page.name === pageManager._defaultPage) {
                        pageManager._go_default();
                    }
                }, error: function (data) {
                    $.toast('加载页面超时', "forbidden");
                }
            });
        },
        _go_default: function () {
            var self = this;
            var page = self._find('name', self._defaultPage);
            for (var stack in self._pageStack) {
                self._pageStack[stack].dom.remove();
            }
            self._pageStack = [];
            self.go(page.name);
        },
        //添加导航队列
        push_nav: function (navigation) {
            this._nav.push(navigation);
            this._nav_bind(navigation);
            return this;
        },
        _nav_action: function (name) {
            var self = this;
            var nav = null;
            for (var i = 0, len = this._nav.length; i < len; i++) {
                if (this._nav[i].name === name) {
                    nav = this._nav[i];
                    break;
                }
            }
            nav = $(nav.template);
            self.$tabbar.removeClass('weui-bar__item_on');
            nav.addClass('weui-bar__item_on');
        },

        //导航队列绑定
        _nav_bind: function (navigation) {
            var self = this;
            var nav = $(navigation.template);
            nav.on('click', function (e) {
                for (var stack in self._pageStack) {
                    self._pageStack[stack].dom.remove();
                }
                self._pageStack = [];
                self.go(navigation.target);
            });
        },
        //刷新页面，指定name则对在栈中单独页面刷新且不影响缓存
        _refresh: function (name) {
            var self = this;
            if (name == null) {
                for (var i = 0, len = this._configs.length; i < len; i++) {
                    if (this._configs[i].save) {
                        if (this._configs[i].action && this._configs[i].navigation == self._point) {
                            page = this._configs[i];
                            $.ajax({
                                type: "GET",
                                cache: false,
                                url: page.action,
                                configs: page,
                                success: function (data) {
                                    $(this.configs.template).html(data);
                                    var class_html = $(data).html();
                                    $('.' + this.configs.name).html(class_html);
                                }, error: function (data) {
                                    console.log(this.configs.action + '加载失败');
                                }
                            });
                        }
                    }
                }
                for(var i = 0, len = this._pageStack.length; i < len; i++){
                    if(self._pageStack[i].save=null){
                        page = self._pageStack[i].config;
                        $.ajax({
                            type: "GET",
                            cache: false,
                            url: page.action,
                            configs: page,
                            success: function (data) {
                                var class_html = $(data).html();
                                $('.' + this.configs.name).html(class_html);
                            }, error: function (data) {
                                console.log(this.configs.action + '加载失败');
                            }
                        });
                    }
                }
            } else {
                for (var i = 0, len = this._pageStack.length; i < len; i++) {
                    if (this._pageStack[i].config.name == name) {
                        page = this._pageStack[i].config;
                        $.ajax({
                            type: "GET",
                            cache: false,
                            url: page.action,
                            configs: page,
                            success: function (data) {
                                var class_html = $(data).html();
                                $('.' + this.configs.name).html(class_html);
                            }, error: function (data) {
                                console.log(this.configs.action + '加载失败');
                            }
                        });
                        break;
                    }
                }
            }

        },

        /*
     *  更新现有堆栈栈顶的url参数
     *  jsonArr: 添加参数数组
     *  demo: PM.updatePara([{'key':'from', 'val':from},
     *  {'key':'to', 'val':to}], [{'key':'recently'}]);
     */
        updatePara: function (paraMap) {
            var last_dom = this._pageStack.slice(-1);
            var search_url = last_dom[0].config.action;
            var url;
            var paraMap = new Map(paraMap);
            var map = new Map();
            if (search_url.indexOf("?") != -1) {
                url = search_url.split('?')[0];
                var search = search_url.substring(search_url.indexOf('?') + 1).split('&');
                for (var i = 0; i < search.length; i++) {
                    if (search[i].indexOf('=') != -1) {
                        var search_arr = search[i].split('=');
                        map.set(search_arr[0], search_arr[1] ? search_arr[1] : '');
                    }
                }
            } else {
                url = search_url;
            }
            paraMap.forEach(function (value, key, Itermap) {
                if (value == '' | value == null) {
                    map.delete(key)
                } else {
                    map.set(key, value);
                }
            });
            search_url = url;
            if (map.size != 0)
                search_url += '?';
            map.forEach(function (value, key, Itermap) {
                search_url = search_url + key + '=' + value + '&';
            })
            search_url = (search_url.charAt(search_url.length - 1) == '&') ? search_url.substring(0, search_url.length - 1) : search_url;
            this._pageStack[this._pageStack.length - 1].config.action = search_url;
        },
        ajax_post: function (data, url) {
            $.ajax({
                type: "POST",
                cache: false,
                url: url,
                data: data,
                success: function (data) {
                    data =  eval('(' + data + ')');
                    //数据提交成功
                    if (data.code == 1) {
                        $.toast(data.msg, function () {
                            pageManager._refresh();
                            if(data.url){
                                pageManager._ajax_go(data.url);
                            }
                        });
                    } else {
                        $.toast(data.msg, 'forbidden');
                    }
                },
                error: function (data) {
                    $.toast('提交数据失败', "forbidden");
                }
            });
        }
    };
});